package com.swf.seed.os.command.impl;

import java.util.Map;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.ParseException;

import com.swf.seed.base.SdLetter;
import com.swf.seed.os.annotation.Command;
import com.swf.seed.os.command.ICommand;
import com.swf.seed.os.util.SpringContextUtils;

@Command("man")
public class ManCommand extends CommandAdaptor {

	@Override
	public void option() {
		options.addOption(SdLetter.h, "help", false, "show other command's usage");
		options.addOption(SdLetter.o, "oneline", false, "show commands in one line,seperator by ,");
		options.addOption(Option.builder(SdLetter.l).longOpt("list").hasArgs().argName("commandName").desc("list supported command").optionalArg(true).build());
		options.addOption(Option.builder(SdLetter.c).longOpt("command").hasArgs().argName("commandName").desc("list command's help").optionalArg(true).build());
	}

	@Override
	void customizedExecute(CommandLine commandLine) throws ParseException {
		if (commandLine.hasOption(SdLetter.c)) {
			String cname = commandLine.getOptionValue(SdLetter.c);
			if (SpringContextUtils.getBeansOfType(ICommand.class).containsKey(cname)){
				CommandAdaptor command = SpringContextUtils.getBean(cname,CommandAdaptor.class);
				command.option();
				HelpFormatter formatter = new HelpFormatter();
				formatter.printHelp(command.getClass().getAnnotation(Command.class)
						.value(),command.getHeader(), command.getOptions(),command.getFooter(),true);
				return;
			}
		}
		boolean oneline = false;
		if (commandLine.hasOption(SdLetter.o)) {
			oneline = true;
		}
		if (commandLine.hasOption(SdLetter.l)) {
			Map<String, ICommand> map = SpringContextUtils.getBeansOfType(ICommand.class);
			int i = 0;
			int size = map.size();
			String commandName = commandLine.getOptionValue(SdLetter.l);
			for (ICommand c : map.values()) {
				String cname= c.getClass().getAnnotation(Command.class).value();
				if (commandName !=null && !cname.matches("^.*"+commandName.replace("*", ".*")+".*$")){
					continue;
				}
				i++;
				if (oneline) {
					if (i < size) {
						System.out.print(cname + ",");
					} else {
						System.out.println(cname);
					}
				} else {
					System.out.println(cname);
				}
			}
		}

	}

}
